﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media;

namespace MyChars
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //
        public class _item
        {
            public string Name {get; set;}
            public string[] Chars {get; set;}
            //
            public _item(string name, string[] chars)
            {
                Name = name;
                Chars = chars;
            }
        };
        ObservableCollection<_item> l = new ObservableCollection<_item>();
        //
        private ConfigFile cfg = new ConfigFile();
        //
        private const int GWL_EXSTYLE = -20;
        private const int WS_EX_NOACTIVATE = 0x08000000;

        [DllImport("user32.dll")]
        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll")]
        public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

        private void OnSourceInitialized(object sender, EventArgs e)
        {
            var interopHelper = new WindowInteropHelper(this);
            int exStyle = GetWindowLong(interopHelper.Handle, GWL_EXSTYLE);
            SetWindowLong(interopHelper.Handle, GWL_EXSTYLE, exStyle | WS_EX_NOACTIVATE);
        }

        [Flags]
        private enum WS_EX { LAYERED = 0x00080000, NOACTIVATE = 0x08000000, TOOLWINDOW = 0x00000080, TRANSPARENT = 0x00000020 };

        System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();
            this.SourceInitialized += this.OnSourceInitialized;
            //
            SetLocalizedTexts();
            //
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 2, 1);
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            list.ItemsSource = l;
            ConfigFile cfg = new ConfigFile();
            cfg.LoadFromConfig(l);


            //Button b = new Button();

            //stack.Children.Add(new Button());
            //stack.Children.Add(new Button());
            //stack.Children.Add(new Button());
            //stack.Children.Add(new Button());
            //stack.Children.Add(new Button());

            WindowState = System.Windows.WindowState.Normal;
            calclateRealWindowHeight();
            PositionOnRightEdge();
            //
            CreateShortcutOnDesktop.CreateShortcutOnDesktop.Do();
            //
            this.Topmost = Properties.Settings.Default.OnTop;
            if (Properties.Settings.Default.LastSelection >= 0 && Properties.Settings.Default.LastSelection < list.Items.Count)
            {
                list.SelectedIndex = Properties.Settings.Default.LastSelection;
                list.ScrollIntoView(list.Items[list.SelectedIndex]);
            }

            //
        }

        private Brush xBorderBrush = null;
        private bool flip= false;
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (null == xBorderBrush) xBorderBrush = list.BorderBrush;
            //
            if(!flip)
            {
                flip=true;
                list.BorderBrush = Brushes.BlueViolet;
            }
            else
            {
                flip=false;
                list.BorderBrush = xBorderBrush;
            }
        }

        // problemem jest pojawianie się fałszywych wyzwoleń eventu po zmianie rozmiarów/położenia okna
        // występują natychmiast po kliknięciu i wybierają następną pozycję na liście
        private static DateTime dtClick = new DateTime();
        private static int prevSelection=0;
        //
        private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
            //
            if (list.SelectedIndex >= 0)
            {
                if ((DateTime.Now - dtClick).Milliseconds < 100)
                {
                    list.SelectedIndex = prevSelection;
                    list.ScrollIntoView(list.Items[list.SelectedIndex]);
                    return;
                }
                //
                list.IsEnabled = false;
                stack.IsEnabled = false;
                //
                stack.Children.Clear();
                foreach (string c in l[list.SelectedIndex].Chars)
                {
                    stack.Children.Add(new Button() { Content = c, Tag = c });
                }
                //
                calclateRealWindowHeight();
                adjustWindowPosition();
                //
                stack.IsEnabled = true;
                list.IsEnabled = true;
                //
                dtClick = DateTime.Now;
                prevSelection = list.SelectedIndex;
            }
        }

        private void stack_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Button b = e.Source as Button;
            if (null == b) return;
            //
            string s = (string)b.Content;
            if (string.IsNullOrEmpty(s)) return;
            //
            if (Keyboard.Modifiers == ModifierKeys.Shift)
            {
                s = s.ToUpperInvariant();
            }
            else if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                window1.Title = string.Format("[0x{0:X}]", (uint)s[0]);
                return;
            }
#if !DEBUG
            System.Windows.Forms.SendKeys.SendWait(s);
#endif
            //
            e.Handled = true;
        }

        private void editConfigurationFileMenuItem_Click(object sender, RoutedEventArgs e)
        {
            cfg.OpenConfigForEditing();
            cfg.LoadFromConfig(l);
        }

        private void writeCleanConfigFileMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if(MessageBoxResult.OK == MessageBox.Show((string)GetLocalizedResource("label_OverwriteConfigFile"),(string)GetLocalizedResource("label_WriteConfigFile"), MessageBoxButton.OKCancel, MessageBoxImage.Question))
            {
                cfg.CreateDefaultConfigFile(true);
                cfg.LoadFromConfig(l);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Properties.Settings.Default.OnTop = this.Topmost;
            Properties.Settings.Default.LastSelection = list.SelectedIndex;
            Properties.Settings.Default.Save();
        }

        private void topmostConfigurationFileMenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            this.Topmost = topmostConfigurationFileMenuItem.IsChecked;
        }


        //
    
    }
}
